# 作者：陈睿-cruise
# 2025年02月14日10时25分05秒
# 2979386061@qq.com
import socket


class TCPServer:
    def __init__(self, host='127.0.0.1', port=8080):
        # 初始化服务器，设置主机和端口
        self.host = host
        self.port = port
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def start(self):
        """启动服务器并开始监听客户端连接"""
        try:
            # 绑定到指定的主机和端口
            self.server_socket.bind((self.host, self.port))
            # 开始监听，最大连接数为 1
            self.server_socket.listen(1)
            print(f"服务器已启动，正在监听 {self.host}:{self.port}...")

            # 等待客户端连接
            client_socket, client_address = self.server_socket.accept()
            print(f"客户端已连接：{client_address}")

            # 处理接收到的数据
            self.handle_client(client_socket)

        except Exception as e:
            print(f"发生错误: {e}")
        finally:
            # 关闭服务器套接字
            self.server_socket.close()
            print("服务器已关闭")

    def handle_client(self, client_socket):
        """与客户端进行交互：接收数据并发送响应"""
        try:
            # 接收客户端发送的数据
            data = client_socket.recv(1024)
            print("接收到的数据:", data.decode())

            # 发送响应数据
            client_socket.send(b"Hello from server!")

        except Exception as e:
            print(f"处理客户端数据时发生错误: {e}")
        finally:
            # 关闭客户端套接字
            client_socket.close()
            print("客户端连接已关闭")


# 启动服务器
if __name__ == '__main__':
    server = TCPServer(host='127.0.0.1', port=8080)
    server.start()
